import Taro, { Component, useState, useEffect, getCurrentPages } from '@tarojs/taro';
import { View, Button, Text, Image, ScrollView } from '@tarojs/components';
import CardBox from '../../components/card-record';
import classnames from 'classnames';
import NavigationBar from '../../components/navigationBar/index';
import Empty from '../../static/public/icon_order.png';

import './index.scss';
import { exchangeCardList, activeCardList, applyCardList, getApplyRecordList, getApplyList, getActiveList, cardArrive } from '../../services/card';
import { timeFormat } from '../../utils/utils';
import { CARD_STATUS, EXP_STATUS, RECORD_STATUS } from '../../utils/config';

let pageData = {
  page: 1,
  page_number: 10
};
let isMore = false;
let isSearch = false;
function CardRecord(props) {

  const navigationBarHeight = Taro.getStorageSync('navigationBarHeight');
  const userInfo = Taro.getStorageSync('userInfo');

  let HeaderTab = userInfo.level === 1 ?
  [{
    key: 4,
    val: '已申领'
  }, {
    key: 5,
    val: '待付款'
  }, {
    key: 6,
    val: '已付款'
  }, {
  key: 1,
  val: '申领记录'
  }] :
  [{
    key: 5,
    val: '待付款'
  }, {
    key: 6,
    val: '已付款'
  }];

  const [ status, setStatus ] = useState(() => {
    if (userInfo.level === 1) {
      return 4;
    } else if (userInfo.level === 2) {
      return 5;
    }
  }); // 头部切换
  const [ cardRecordList, setCardRecordList ] = useState([]);
  const [ start, setStart ] = useState(['开始时间'])
  const [ end, setEnd ] = useState(['截止时间'])

  let { flag } = props;
  if (flag === 1) {
    // 刷新
    pageData.page = 1;
    isSearch = false;
    setStart('开始时间')
    setEnd('截止时间')
    if (userInfo.level === 1 && status === 1) {
      props.onChanged();
      getApplyList({
        ...pageData,
      }).then(res => {
        renderList(res, false, status)
      })
    } else {
      init()
    }
  } else if (flag === 2) {
    // 加载
    onScrollToLower()
  } else {

  }

  useEffect(() => {
    pageData = {
      page: 1,
      page_number: 10
    };
    isMore = false;
    isSearch = false;
    let pages = Taro.getCurrentPages();
    let type = null;
    if (pages[pages.length - 1].options) {
      type = pages[pages.length - 1].options.type || null;
    }
    if (type) {
      handleTabChange(1, false);
    } else {
      init()
    }
  }, [])

  useEffect(() => {
    if (start.indexOf('-') >= 0 && end.indexOf('-') >= 0) {
      if (new Date(start).getTime() >= new Date(end).getTime()) {
        Taro.showToast({
          title: '开始时间不能大于截止时间',
          icon: 'none'
        })
      } else {
        isSearch = true;
        handleTabChange(status, true)
      }
    }
  }, [end, start])

  function renderList(res, isConcat, status) {
    res.list.forEach(card => {
      card.time = timeFormat(card.update_time)
    })
    console.log(res.list)
    if (isConcat) {
      let temp = cardRecordList.concat(res.list)
      setCardRecordList(temp)
      isMore = temp.length < res.total
    } else {
      setCardRecordList(res.list)
      isMore = res.list.length < res.total
    }
    if (userInfo.level !== 0) {
      setStatus(status)
    }
    pageData.page++
  }

  function init() {
    props.onChanged();
    if (userInfo.level === 1) {
      console.log(status, 'status')
      getApplyRecordList({
        ...pageData,
        status,
      }).then(res => {
        renderList(res, false, status)
      })
    } else if (userInfo.level === 2) {
      exchangeCardList({
        ...pageData,
        status,
      }).then(res => {
        renderList(res, false, status)
      })
    } else if (userInfo.level === 0) {
      getActiveList({
        ...pageData
      }).then(res => {
        renderList(res, false)
      })
    }
  }

  function handleTabChange(key, isSearchTime) {
    isMore = false
    pageData.page = 1
    let data = {};
    if (isSearchTime) {
      data = {
        start_time: parseInt(new Date(start).getTime() / 1000, 10),
        end_time: parseInt(new Date(end).getTime() / 1000, 10),
      }
    } else {
      isSearch = false;
      setStart('开始时间')
      setEnd('截止时间')
    }
    if (userInfo.level === 1) {
      if (key === 1) {
        getApplyList({
          ...pageData,
          ...data,
        }).then(res => {
          renderList(res, false, key)
        })
      } else {
        getApplyRecordList({
          ...pageData,
          status: key,
          ...data,
        }).then(res => {
          renderList(res, false, key)
        })
      }
    } else if (userInfo.level === 2) {
      exchangeCardList({
        ...pageData,
        status: key,
        ...data,
      }).then(res => {
        renderList(res, false, key)
      })
    }
  }

  function apply() {
    Taro.navigateTo({
      url: '/subPackageWork/pages/apply/index'
    })
  }

  function calcRecordStatus(card) {
    if (card.status === 2) {
      if (card.exp_status === 1) {
        return 'showArrive'; // 确认到货
      } else {
        return EXP_STATUS[card.exp_status];
      }
    } else {
      return RECORD_STATUS[card.status];
    }
  }

  function onScrollToUpper() {
    console.log('refresh')
  }

  function onScrollToLower() {
    if (isMore) {
      let data = {};
      if (isSearch) {
        data = {
          start_time: parseInt(new Date(start).getTime() / 1000, 10),
          end_time: parseInt(new Date(end).getTime() / 1000, 10),
        }
      }
      if (userInfo.level === 1) {
        if (status === 1) {
          getApplyList({
            ...pageData,
            ...data,
          }).then(res => {
            renderList(res, true, status)
          })
        } else {
          getApplyRecordList({
            ...pageData,
            ...data,
            status,
          }).then(res => {
            renderList(res, true, status)
          })
        }
      } else if (userInfo.level === 2) {
        exchangeCardList({
          ...pageData,
          status,
          ...data,
        }).then(res => {
          renderList(res, true, status)
        })
      } else if (userInfo.level === 0) {
        getActiveList({
          ...pageData
        }).then(res => {
          renderList(res, true)
        })
      }
    }
  }

  function handleDate(type, e) {
    console.log(type, e)
    if (type === 0) {
      // start
      setStart(e.detail.value)
    } else {
      // end
      setEnd(e.detail.value)
    }
  }

  function userCardArrive(id) {
    console.log(id)
    cardArrive({
      id
    }).then(res => {
      let temp = [...cardRecordList]
      let tempCard = temp.find(item => {
        return item.id === id
      })
      tempCard.status = 2;
      tempCard.exp_status = 2;
      setCardRecordList(temp)
    })
  }


  return (
    <View className='card-record' style={`margin-top: ${navigationBarHeight}`}>
      <NavigationBar text="我的卡券" />
      {
        userInfo.level === 0 ? '' : <View className="top-wrapper" style={`top: ${navigationBarHeight}`}>
          <View className="header">
            {
              HeaderTab.map((res) => (
                <View className="header-box" key={res.key} onClick={() => handleTabChange(res.key, false)}>
                  <View className={classnames({
                    'content': true,
                    'active': res.key === status
                  })}>{res.val}</View>
                </View>
              ))
            }
          </View>
          <View className="select-box">
            <Picker mode='date' onChange={(e) => { handleDate(0, e) }}>
              <View className={classnames({
                'start': true,
                'active': start.indexOf('开始时间') < 0
              })}>
                {start}
              </View>
            </Picker>
            <View className="icon">~</View>
            <Picker mode='date' onChange={(e) => { handleDate(1, e) }}>
              <View className={classnames({
                'end': true,
                'active': end.indexOf('截止时间') < 0
              })}>
                {end}
              </View>
            </Picker>
          </View>
        </View>
      }
      {/* {userInfo.level === 1 && status === 1 && <View className="apply-card" onClick={apply}>申领卡</View>} */}
      {/* <ScrollView
        className='card-list'
        style={`top: ${(userInfo.level === 1 || userInfo.level === 2) ? '70px' : '0'}`}
        scrollY
        scrollWithAnimation
        onScrollToLower={onScrollToLower}
        onScrollToUpper={onScrollToUpper}
      > */}
      <View className="card-list" style={`top: ${(userInfo.level === 1 || userInfo.level === 2) ? '70px' : '0'}`}>
      {
        !cardRecordList.length && <View className="empty-box">
          <Image src={Empty} className="empty" />
          <View className="tip">暂无信息</View>
        </View>
      }
      {
        userInfo.level === 1 && cardRecordList.length ? cardRecordList.map(card => {
          if (card) return <CardBox
                  key={card.id}
                  agency={status !== 1 ? `${card.has_apply_user.nickname}(${card.has_apply_user.mobile})` : ''}
                  type={status === 1 ? 1 : 2}
                  time={card.time}
                  cardId={card.id}
                  cardType={card.has_card_type.attr_name}
                  number={status === 1 ? card.number : card.card_no}
                  status={status === 1 ? calcRecordStatus(card) : CARD_STATUS[card.status]}
                  arrive={userCardArrive}
                />
        }) :
        cardRecordList.map(card => {
          if (card) return <CardBox
                  key={card.id}
                  type={3}
                  time={card.time}
                  cardType={card.has_card_type.attr_name}
                  number={card.card_no}
                  status={CARD_STATUS[card.status]}
                />
        })
      }
      {/* </ScrollView> */}
      </View>
    </View>
  )
}

CardRecord.config = {
  navigationBarTitleText: '我的兑换卡',
}

export default CardRecord;
